package y2015.day_15.输入输出流02;

import org.junit.jupiter.api.Test;

import java.io.*;

/*
 * FileRead和FileWrite是字符流，接收的是字符流。可以用来复制文本文件，但不能复制图片
 */

/**
 * 文件复制
 */
public class FileCopy {
    @Test
    public void main() throws Exception {
        File from = new File("C:\\Documents and Settings\\tarena\\桌面", "dou.png");
        File dir = new File("E:\\dou\\Sa");
        File to = new File(dir, "nima.png");
        copy(from, dir, to);
    }

    /**
     * 复制文件的方法
     *
     * @throws IOException
     */
    private static void copy(File from, File dir, File to) throws IOException {
        byte fio[];

        FileInputStream refrom = null;
        FileOutputStream writeto = null;
        try {
            refrom = new FileInputStream(from);
            fio = new byte[(int) from.length()];
            refrom.read(fio);//
            if (!to.exists()) {//如果路径或文件不存在则创建
                dir.mkdirs();
                to.createNewFile();
                writeto = new FileOutputStream(to);
                writeto.write(fio);
            } else {
                writeto = new FileOutputStream(to);
                writeto.write(fio);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            refrom.close();
            writeto.close();
        }


    }
}

